import { TokenStorageService } from './token-storage.service';
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable, of } from 'rxjs';
import { filter, share } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class TokenService {
  protected token$ = new BehaviorSubject<string>(null);

  constructor(private store: TokenStorageService) { }

  change(): Observable<string> {
    return this.token$.pipe(
      filter(value => !!value),
      share()
    );
  }

  clear(): Observable<null> {
    this.store.clear();
    this.publishStoredToken();
    return of(null);
  }

  get(): Observable<string> {
    return of(this.store.get());
  }

  set(token: string): Observable<null> {
    this.store.set(token);
    this.publishStoredToken();
    return of(null);
  }

  protected publishStoredToken(): void {
    this.token$.next(this.store.get());
  }
}
